// 将数组按照VueRouter格式转成树
export const ArrayFormatVueRouter = (
  array,
  pid = null,
  parentStorey = null
) => {
  return array.reduce((prev, cur) => {
    if ( Number(cur.meta.pid) == Number(pid)) {
      let storey = parentStorey ?? 0;
      let meta = cur.meta;
      cur.meta.storey = storey;
      if (meta.type) {
        cur.component = () =>
          import(`@/pages/layout/components/router-view/router-view.vue`);
      } else {
        cur.component = () => import(`@/pages/${cur.meta.component}.vue`);
      }
      let {
        // redirect_name,
        redirect_state,
        // redirect_target,
        redirect_type,
        redirect_url,
      } = cur.meta.redirect;

      if (redirect_state && redirect_type && redirect_url) {
        cur.redirect = redirect_url;
      }
      const children = ArrayFormatVueRouter(array, meta.id, ++storey);
      cur.children = children;
      prev.push(cur);
    }
    return prev;
  }, []);
};
// 根据child的ID 寻找祖先ID
export const childIdGeTAncestorsId = (array, oid = null) => {
  console.log("childIdGeTAncestorsId", oid);
  let orn = array.find((item) => item.id == oid);
  let { id, pid } = orn;
  if (pid) {
    return childIdGeTAncestorsId(array, pid);
  } else {
    return id;
  }
};

// 格式化数据
export const formatMenuItem = (item) => {
  let { name = "", path = "", redirect = null, component = null } = item;
  let meta = item.meta;
  let display = meta?.display ?? {};
  let componentFilePath = meta.component
    ? `@/pages/${meta.component}.vue`
    : null;
  return {
    name,
    path,
    redirect,
    component,
    meta: {
      id: meta.id,
      pid: meta.pid ?? null,
      title: meta.title ?? "",
      icon: meta.icon ?? "",
      component: meta.component,
      componentFilePath,
      storey: 0, // 菜单层级
      display: {
        // 显示
        ifMenuBar: display?.ifMenuBar ?? false, // 是否为菜单
        breadcrumb: display?.breadcrumb ?? true, // 面包屑显示
        navigator: display?.navigator ?? true, // 导航菜单显示
        navigatorRightIcon: display?.navigatorRightIcon ?? false, // 菜单右侧箭头图标
        normalIconClass: meta.icon ?? "", // 正常状态菜单图标
        hoverIconClass: meta.icon ?? "", // hover状态菜单图标
        activedChangeId: null, // 当菜单激活时,将激活的ID指向这个ID，用于高亮其他ID的菜单
        childrenDevelop: display?.childrenDevelop ?? false,
      },
      camouflage: {
        // 包装
        type: "",
        tag: "",
        href: "",
        target: "_blank",
      },
      skip: {
        // 页面跳转
        type: "push", // 向路由表示，当路由跳转时以那种方式进行跳转
      },
      page: {
        // 页面配置
      },
      keepAlive: {
        // 缓存
      },
      sort: {
        // 排序
        top: false, // 置顶
        index: null, // 排序Index
      },
    },
  };
};
export default {
  childIdGeTAncestorsId,
  ArrayFormatVueRouter,
  formatMenuItem,
};
